package com.delu.MessageMQ;

import com.alibaba.fastjson.JSONObject;
import com.delu.dto.OrderPayDTO;
import com.delu.entity.Message;
import com.delu.service.phoneMessageService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by zhangpk on 2021/12/22
 **/
@Component
@RocketMQMessageListener(topic = "sendMessage",consumerGroup = "springcould_group")
public class SendMessageMQConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private com.delu.service.phoneMessageService phoneMessageService;

    @Override
    public void onMessage(String message) {
        System.out.println("消息接收成功" + message);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {

        consumer.setInstanceName("testTopic-tag1");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list,
                                                            ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt message = list.get(0);
                message.getBody();//获取消息实体类,这个时候不支持直接接收对象
                message.getMsgId();//消息的id,通过此id我们结合redis可以保证消费幂等性
                message.getReconsumeTimes();//消息重试的次数
                try{
                    String messageBody = new String(message.getBody(), "utf-8");
                    Message message1 = JSONObject.parseObject(messageBody, Message.class);
                    phoneMessageService.sendPhoneMessage(message1.getPhone(),message1.getBody());
                    System.out.println("ACK消息消费成功!!!" + messageBody);
                }catch (Exception e){
//                    e.printStackTrace();
                    System.out.println("消息消费失败,请稍后重试");
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
